<template>
  <view class="body">
    <view class="date_top">
      <view class="date_btn" @tap="showCalendar">
        <text class="date">{{ isToday(state.today) }}</text>
        <image
          class="img_arrow"
          v-if="!state.datepickShow"
          src="https://ainengli.hzjrsw.com/jkhx/common/arrow_down.png"
        />
        <image
          class="img_arrow"
          v-if="state.datepickShow"
          src="https://ainengli.hzjrsw.com/jkhx/common/arrow_up.png"
        />
      </view>
    </view>
    <up-popup :show="state.dateShow" :round="16" mode="bottom" @close="closeCalendar">
      <uni-calendar
        :date="parseTime(state.today, '{y}-{m}-{d}')"
        :showMonth="false"
        :selected="state.dateSelects"
        @change="setDate"
      />
    </up-popup>

    <view class="seven">
      <view
        v-for="(item, index) in state.weekList"
        :key="index"
        :class="['items', index == state.active ? 'active' : '']"
        >{{ WEEK[item - 1] }}</view
      >
    </view>
    <view v-if="state.dateSelects.length == 0" class="nodata">
      <image class="img_nodata" src="https://ainengli.hzjrsw.com/jkhx/noData.png" />
      <view class="nodata_text">还没有记录</view>
      <view class="nodata_text">请点击屏幕下方按钮来添加</view>
    </view>
    <view class="today_sport" v-else>
      <view
        class="sport-item"
        v-for="(item, index) in state.dateSelects"
        :key="index"
        @tap="toDetail(item)"
      >
        <view class="sport-item-left">
          <text class="title">{{ item.sportName }}</text>
          <text class="desc">{{ item.duration || '--' }}分钟 {{ item.consume }}千卡</text>
        </view>
        <view class="sport-item-right">
          <img
            class="img"
            src="https://ainengli.hzjrsw.com/jkhx/common/my-arrow-right.png"
            alt=""
          />
        </view>
      </view>
    </view>
    <view class="fixed" @tap="recordSports">
      <button class="fix-btn">记运动</button>
    </view>

    <!-- 运动设置 -->
    <up-popup :show="state.setShow" :round="16" mode="bottom" closeable @close="close">
      <view class="food_info">
        <view class="title"> 运动信息 </view>
        <view class="info_top">
          <view class="name">{{ state.addSport.sportName }}</view>
        </view>
        <view class="input_info">
          <input
            type="digit"
            class="weight_input"
            :focus="state.tipFocus"
            :maxlength="4"
            @input="onInput"
            :adjustPosition="false"
            @keyboardheightchange="onKey"
            v-model="state.addSport.duration"
          />
          <view class="unit">分钟</view>
          <view class="hot">(根据您的体重计算，消耗约{{ state.addSport.energy || '--' }}千卡)</view>
        </view>
        <button class="submit" @tap="sportSelect">确定</button>
        <view class="bottom_box" :style="{ height: `${state.bottomHeight}rpx` }" />
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { throttle, deepCopy, parseTime } from '@/utils/tools'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { getSportRecord, calculateEnergy, saveSportRecord } from './sportsInfo.api'

const WEEK = ['一', '二', '三', '四', '五', '六', '日']

const state = reactive({
  now: new Date(),
  yearsAgo: new Date().setFullYear(new Date().getFullYear() - 1),
  today: new Date(),
  datepickShow: false,
  dateShow: false,
  dateSelects: [],
  show: false,
  setShow: false,
  addSport: {},
  userInfo: {},
  active: 0,
  weekList: [],
  tipFocus: false,
  bottomHeight: 0
})

const editInfo = reactive({
  date: '',
  type: '',
  foodInfo: {}
})

onShow(() => {
  state.userInfo = uni.getStorageSync('userInfo')
    ? JSON.parse(uni.getStorageSync('userInfo')).patientInfo
    : {}
  state.show = false
  getTime()
  getData()
  const currentMouth = {
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1
  }
  // getMouthDate(currentMouth)
})

const showCalendar = () => {
  state.datepickShow = !state.datepickShow
  state.dateShow = !state.dateShow
}
const closeCalendar = () => {
  state.dateShow = false
  state.datepickShow = false
}

const getData = () => {
  const params = {
    empi: state.userInfo.empi,
    date: parseTime(state.today, '{y}-{m}-{d}')
  }

  getSportRecord(params).then((res: any) => {
    state.dateSelects = res.data
  })
}

const getTime = () => {
  const day = state.today.getDay()
  state.weekList = [1, 2, 3, 4, 5, 6, 7]
  state.weekList.forEach((item, index) => {
    if (day === 0) {
      state.active = 6
    }
    if (day == item) {
      state.active = index
    }
  })
}
const isToday = (val) => {
  // 今天昨天前天转换
  const select = parseTime(val, 'yyyy/MM/dd') + ' 00:00:00'
  const today = parseTime(state.now, 'yyyy/MM/dd') + ' 00:00:00'
  if (new Date(today).getTime() - new Date(select).getTime() == 0) {
    return '今天'
  } else if (new Date(today).getTime() - new Date(select).getTime() == 86400000) {
    return '昨天'
  } else if (new Date(today).getTime() - new Date(select).getTime() == 172800000) {
    return '前天'
  } else {
    return parseTime(val, '{y}-{m}-{d}')
  }
}
const setDate = (e) => {
  state.datepickShow = false
  state.dateShow = false
  state.today = new Date(e.fulldate)
  console.log(state.today, e.fulldate)
  getTime()
  getData()
}

const toDetail = async (val: any) => {
  state.addSport = val
  state.setShow = true
  await getcalculateEnergy()
  setTimeout(() => {
    // 解决弹窗打开时，input无法获取焦点问题
    state.tipFocus = true
  }, 100)
}

const onKey = (e) => {
  const sys = uni.getSystemInfoSync()
  // 自定义弹出键盘事件
  if (e.detail.height) {
    state.bottomHeight = e.detail.height * 2 - sys.safeAreaInsets.bottom * 2 - 36
  } else {
    state.bottomHeight = 0
  }
}
const onInput = throttle(async (e) => {
  if (e.detail.value * 1 > 3000) {
    state.addSport.duration = 3000
  }
  if (!state.addSport.duration) {
    state.addSport.energy = 0
  } else {
    await getcalculateEnergy()
  }
}, 200)

// 计算能量
const getcalculateEnergy = async () => {
  calculateEnergy({
    empi: state.userInfo.empi,
    actionType: state.addSport.actionType,
    sex: state.userInfo.gender == '男性' ? 1 : 2,
    minutes: Number(state.addSport.duration)
  }).then(async (res) => {
    state.addSport.energy = res.data.energyValue
  })
}

const close = () => {
  state.setShow = false
  state.tipFocus = false
  state.bottomHeight = 0
}

const sportSelect = throttle(() => {
  const data = [
    {
      id: state.addSport.id,
      takeTime: state.addSport.takeTime,
      sportId: state.addSport.sportId,
      sportName: state.addSport.sportName,
      sportType: state.addSport.sportType,
      consume: state.addSport.consume,
      empi: state.addSport.empi,
      duration: state.addSport.duration
    }
  ]

  saveSportRecord(data).then((res) => {
    state.setShow = false
    state.tipFocus = false
    getData()
  })
}, 300)
const recordSports = (val: string) => {
  uni.navigateTo({
    url:
      '/module/src/pages/sports/sportsInfo/detail?food=' +
      val +
      '&date=' +
      parseTime(state.today, '{y}-{m}-{d}')
  })
}
</script>

<style lang="scss" scoped>
.body {
  height: 100vh;
  padding: 0 32rpx;
  padding-bottom: calc(156rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(156rpx + env(safe-area-inset-bottom));

  .date_top {
    text-align: center;

    .date_btn {
      box-sizing: border-box;
      display: inline-block;
      height: 60rpx;
      padding: 0 32rpx;
      margin: 24rpx auto;
      line-height: 60rpx;
      text-align: center;
      background: #fff;
      border-radius: 38rpx;

      .date {
        font-size: 28rpx;
        font-weight: 400;
        color: #222;
      }

      .img_arrow {
        width: 24rpx;
        height: 24rpx;
        margin-left: 16rpx;
      }
    }
  }

  .seven {
    display: flex;
    gap: 24rpx;
    justify-content: space-between;
    margin-bottom: 26rpx;

    .items {
      box-sizing: border-box;
      width: 77rpx;
      height: 76rpx;
      font-size: 28rpx;
      font-weight: 400;
      line-height: 76rpx;
      color: #222;
      text-align: center;
      background: #fff;
      border-radius: 12rpx;
    }

    .active {
      color: #fff;
      background: #00d1b6;
    }
  }

  .today_sport {
    position: relative;
    box-sizing: border-box;
    height: calc(100vh - 280rpx);
    overflow: hidden auto;

    .sport-item {
      width: 100%;
      padding: 32rpx;
      background-color: #fff;
      border-radius: 16rpx;
      margin-bottom: 24rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-direction: row;

      .sport-item-left {
        display: flex;
        flex-direction: column;
        .title {
          font-weight: 500;
          font-size: 30rpx;
          color: #333333;
          margin-bottom: 10rpx;
        }

        .desc {
          font-weight: 400;
          font-size: 28rpx;
          color: #999999;
        }
      }

      .sport-item-right {
        display: flex;
        align-items: center;
        .img {
          width: 32rpx;
          height: 32rpx;
        }
      }
    }
  }

  .nodata {
    text-align: center;

    .img_nodata {
      width: 320rpx;
      height: 240rpx;
      margin-top: 60rpx;
    }

    .nodata_text {
      font-size: 28rpx;
      font-weight: 400;
      color: #666;
    }
  }

  .fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 10;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    // gap: 24rpx;
    justify-content: space-between;
    width: 100%;
    padding: 24rpx 32rpx;
    padding-bottom: calc(68rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(68rpx + env(safe-area-inset-bottom));
    background: #fff;

    .fix-btn {
      width: 100%;
      font-size: 32rpx;
      font-weight: 700;
      color: #fff;
      background: #00d1b6;
      border-radius: 44rpx;
    }
  }

  ::v-deep .u-popup {
    // 设置重量弹窗
    .food_info {
      padding: 0 32rpx;

      .title {
        width: 100%;
        height: 104rpx;
        font-size: 30rpx;
        font-weight: 500;
        line-height: 104rpx;
        color: #333;
        text-align: center;
      }

      .info_top {
        .name {
          margin-bottom: 10rpx;
          font-size: 30rpx;
          font-weight: 500;
          color: #222;
        }

        .power {
          font-size: 28rpx;
          font-weight: 400;
          color: #666;
        }
      }

      .info_detail {
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        padding: 20rpx 0;
        margin: 26rpx 0 30rpx;
        font-size: 24rpx;
        font-weight: 400;
        color: #999;
        border-top: 1rpx solid #e5e6eb;
        border-bottom: 1rpx solid #e5e6eb;

        .detail_item {
          flex: 1;
          text-align: center;

          .text {
            margin-bottom: 10rpx;
          }
        }
      }

      .input_info {
        position: relative;
        text-align: center;

        .weight_input {
          width: 200rpx;
          height: 84rpx;
          margin: 0 auto;
          font-size: 60rpx;
          font-weight: 500;
          color: #1cd7ae;
          border-bottom: 4rpx solid #1cd7ae;
        }

        .unit {
          position: absolute;
          top: 0;
          right: 235rpx;
          font-size: 24rpx;
          font-weight: 500;
          color: #1cd7ae;
        }

        .hot {
          margin-top: 16rpx;
          font-size: 24rpx;
          font-weight: 400;
          color: #666;
        }
      }

      .submit {
        width: 100%;
        height: 88rpx;
        padding: 0 !important;
        margin: 76rpx 0 32rpx;
        font-size: 32rpx !important;
        font-weight: 500;
        line-height: 88rpx !important;
        color: #fff;
        background: #00d1b6;
        border-radius: 50rpx;
      }
    }
    .u-popup__content {
      overflow: hidden;

      .uni-calendar {
        .uni-calendar__header {
          .uni-calendar__header-text {
            font-size: 30rpx !important;
          }
        }

        .uni-calendar__box {
          .uni-calendar__weeks-day-text {
            font-size: 30rpx !important;
          }

          .uni-calendar-item__weeks-box-text {
            font-size: 30rpx !important;
          }

          .uni-calendar-item--isDay {
            border-radius: 8rpx;
          }
        }
      }
    }
  }

  ::v-deep .dialog-close {
    display: none;
  }

  ::v-deep .uni-calendar-item--isDay {
    background: #00d1b6;
  }

  ::v-deep .uni-calendar-item--checked {
    background: #00d1b6;
  }

  ::v-deep .uni-date-editor {
    width: 254rpx;
    margin: 0 auto;
  }

  ::v-deep .uni-calendar-item--isDay-text {
    color: #00d1b6;
  }

  ::v-deep .uni-calendar-item--isDay .uni-calendar-item--isDay-text {
    color: #fff;
  }

  ::v-deep .uni-calendar-item__weeks-box-circle {
    background: #00d1b6;
  }

  ::v-deep .uni-calendar-item__weeks-box .uni-calendar-item--checked {
    background-color: #00d1b6;
  }

  ::v-deep .uni-calendar__weeks-day {
    background: #ebfbf9;

    .uni-calendar__weeks-day-text {
      color: #00d1b6;
    }
  }

  ::v-deep .uni-datetime-picker--btn {
    height: 88rpx;
    line-height: 88rpx;
    background-color: #00d1b6;
  }

  ::v-deep .uni-progress-bar,
  ::v-deep .uni-progress-inner-bar {
    border-radius: 100rpx;
  }

  ::v-deep .u-icon__icon {
    top: 16rpx !important;
    font-size: 40rpx !important;
  }
}
</style>
